<template>
  <!-- 新增按钮 -->
  <el-button type="primary" plain @click="openInsertDialog()" style="margin-bottom: 30px">新增班级</el-button>

  <el-input v-model="searchText" style="width: 240px;margin-left: 20px;margin-bottom: 30px" placeholder="请输入班级名" />
  <el-button style="margin-left: 20px;margin-bottom: 30px" type="primary" @click="searchClass()" round>搜索</el-button>

  <el-table :data="classTableData" stripe style="width: 100%" v-if="classTableData.length > 0">
    <el-table-column prop="name" label="班级名" wixdth="180" />
    <el-table-column prop="classCode" label="班级代码" wixdth="180" />
    <el-table-column prop="college" label="学院" wixdth="180" />
    <el-table-column prop="major" label="专业" wixdth="180" />
    <el-table-column prop="studentCount" label="人数" wixdth="180" />
    <el-table-column prop="headTeacherName" label="班主任" wixdth="180" />
    <el-table-column fixed="right" label="操作" min-width="180" align="center">
      <template #default="scope">
        <el-button link type="primary" @click="addStudent(scope.row)">添加学生</el-button>
        <el-button link type="primary" @click="deleteStudent(scope.row)">删除学生</el-button>
        <el-button link type="primary" @click="updateClass(scope.row)">修改</el-button>
        <el-button link type="primary" @click="deleteClass(scope.row.id)" >删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页条 -->
  <el-pagination
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next"
      @current-change="handlePageChange"
      style="margin-top: 20px; justify-content: center;"
      v-if="classTableData.length > 0"
  />
  <el-empty :image-size="200" v-else style="margin-top: 175px"/>

  <!-- 修改页弹窗 -->
  <el-dialog v-model="ClassDetailUpdateVisible" title="修改学生信息" width="1000">
    <div>
      <el-form :model="classData" :rules="rules" ref="updateFormRef" label-position="left" label-width="80px" >
        <el-form-item label="班级名" prop="name" >
          <el-input v-model="classData.name" />
        </el-form-item>
        <el-form-item label="班级代码" prop="classCode">
          <el-input v-model="classData.classCode" />
        </el-form-item>
        <el-form-item label="学院" prop="college">
          <el-input v-model="classData.college" />
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="classData.major" />
        </el-form-item>
        <el-form-item label="班级人数" prop="studentCount">
          <el-input v-model="classData.studentCount" disabled/>
        </el-form-item>
        <el-form-item label="班主任" prop="headTeacherTno">
          <el-select v-model="classData.headTeacherTno" placeholder="请选择班主任" style="width: 100%">
            <el-option
                v-for="teacher in teacherList"
                :key="teacher.tno"
                :label="`${teacher.tno} - ${teacher.name}`"
                :value="teacher.tno"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div>
        <el-button @click="ClassDetailUpdateVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateClassRel()">
          修改
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 新增页弹窗 -->
  <el-dialog v-model="ClassInsertDialogVisible" title="新增" width="1000">
    <div>
      <el-form :model="classData" :rules="rules" ref="insertFormRef" label-position="left" label-width="80px" >
        <el-form-item label="班级名" prop="name" >
          <el-input v-model="classData.name" />
        </el-form-item>
        <el-form-item label="班级代码" prop="classCode">
          <el-input v-model="classData.classCode" />
        </el-form-item>
        <el-form-item label="学院" prop="college">
          <el-input v-model="classData.college" />
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="classData.major" />
        </el-form-item>
        <el-form-item label="班级人数" prop="studentCount">
          <el-input v-model="classData.studentCount" disabled/>
        </el-form-item>
        <el-form-item label="班主任" prop="headTeacherTno">
          <el-select v-model="classData.headTeacherTno" placeholder="请选择班主任" style="width: 100%">
            <el-option
                v-for="teacher in teacherList"
                :key="teacher.tno"
                :label="`${teacher.tno} - ${teacher.name}`"
                :value="teacher.tno"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div>
        <el-button @click="ClassInsertDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="insertClass()">
          新增
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 新增学生页面弹窗 -->
  <el-dialog v-model="ClassStudentManageVisible" title="添加学生" width="1000">
    <div>
      <el-table :data="studentTableData" stripe style="width: 100%" v-if="studentTableData.length > 0" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="姓名" wixdth="180" />
        <el-table-column prop="sno" label="学号" wixdth="180" />
        <el-table-column prop="college" label="学院" wixdth="180" />
        <el-table-column prop="major" label="专业" wixdth="180" />
        <el-table-column prop="inputTime" label="入学时期" wixdth="180" />
      </el-table>
      <el-empty :image-size="200" v-else style="margin-top: 50px"/>
    </div>
    <template #footer>
      <div>
        <el-button @click="ClassStudentManageVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="addStudentRel()" :disabled="selectedStudents.length === 0">
          确认添加
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 删除学生页面弹窗 -->
  <el-dialog v-model="ClassStudentDeleteVisible" title="删除学生" width="1000">
    <div>
      <el-table :data="studentTableData" stripe style="width: 100%" v-if="studentTableData.length > 0" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="姓名" wixdth="180" />
        <el-table-column prop="sno" label="学号" wixdth="180" />
        <el-table-column prop="college" label="学院" wixdth="180" />
        <el-table-column prop="major" label="专业" wixdth="180" />
        <el-table-column prop="inputTime" label="入学时期" wixdth="180" />
      </el-table>
      <el-empty :image-size="200" v-else style="margin-top: 50px"/>
    </div>
    <template #footer>
      <div>
        <el-button @click="ClassStudentManageVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="deleteStudentRel()" :disabled="selectedStudents.length === 0">
          确认删除
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>


<script lang="ts" setup>
import {onMounted, ref} from "vue";
import axios from '../utils/http.js';
import {ElMessage, ElPagination} from 'element-plus';
import { genFileId } from 'element-plus'
import type { UploadProps, UploadRawFile } from 'element-plus'

// 输入的搜索文字
const searchText = ref('');

//班级表格数据
const classTableData = ref([{
  name: '',
  classCode: '',
  college: '',
  major: '',
  studentCount: '',
  headTeacherName: ''
}])

// 学生列表数据（没有班级的）
const studentTableData = ref([{
  name: '',
  sno: '',
  college: '',
  major: '',
  inputTime: ''
}])

// 选中的学生列表
const selectedStudents = ref([])

// 当前操作的班级信息
const currentClass = ref()


//一个班级的信息
const classData = ref()

// 教师列表数据
const teacherList = ref([])

// 新增一个专门用于新增的初始化方法
const initClassForCreate = () => {
  classData.value = {
    name: '',
    classCode: '',
    college: '',
    major: '',
    studentCount: '',
    headTeacherName: '',
    headTeacherTno: ''
  }
}

// 新增按钮的点击事件
const openInsertDialog = () => {
  ClassInsertDialogVisible.value = true
  initClassForCreate() // 仅在这里初始化
}

//分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

//决定是否弹出班级修改页
const ClassDetailUpdateVisible = ref(false);
//决定是否弹出班级增加页
const ClassInsertDialogVisible = ref(false);
//决定是否弹出班级增加学生页
const ClassStudentManageVisible = ref(false);
//决定是否弹出班级删除学生页
const ClassStudentDeleteVisible = ref(false);



// 定义表单引用
const updateFormRef = ref(null)
const insertFormRef = ref(null);

// 验证规则
const rules = {
}

/**
 * 初始化加载数据
 */
onMounted(() => {
  fetchData()
  fetchTeacherList()
})


/**
 * 获取教师列表
 */
const fetchTeacherList = async () => {
  try {
    const response = await axios.get('/tea/teacher/list')
    console.log('教师列表:', response);
    teacherList.value = response.data.data || [];
  } catch (error) {
    console.error('获取教师列表失败:', error);
    ElMessage.error('获取教师列表失败')
  }
}

/**
 * 获取数据
 */
const fetchData = async () => {
  try {
    const response = await axios.get('/class/class', {
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    })
    console.log(response);
    classTableData.value = response.data.data;
    total.value = Number(response.data.message);
    console.log("Total:", total.value, "Type:", typeof total.value);
  } catch (error) {
    console.error('获取数据失败:', error);
  }
}

/**
 * 搜索班级
 */
const searchClass = async () => {
  if (searchText.value === '' || searchText.value.length <= 0) {
    fetchData();
    return;
  }
  try {
    const response = await axios.get('/class/class/search/' + searchText.value, {
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    })
    console.log(response);
    classTableData.value = response.data.data;
    total.value = Number(response.data.message);
    console.log("Total:", total.value, "Type:", typeof total.value);
  } catch (error) {
    console.error('获取数据失败:', error);
  }
}

/**
 * 页码变化处理
 * @param page
 */
const handlePageChange = (page) => {
  currentPage.value = page
  fetchData()
}

/**
 * 删除班级
 * @param id
 */
const deleteClass = async (id) => {
  try {
    //先询问是否删除
    if(window.confirm('是否删除')){
      const response = await axios.delete('/class/class/' + id)
      console.log(response);
      if (response.data.code === 200){
        ElMessage.success("删除成功")
        fetchData();
      } else {
        ElMessage.error("删除失败")
      }
    }
  } catch (error) {
    console.log(error)
    ElMessage.error("删除失败：" + error)
  }
}

/**
 * 修改，打开弹窗
 * @param rowData
 */
const updateClass = (rowData) => {
  ClassDetailUpdateVisible.value = true;
  classData.value = rowData
}

/**
 * 修改，真正修改
 */
const updateClassRel = async () => {
  //将classData打包送给后端
  // 验证表单
  await updateFormRef.value.validate()

  try {
    const response = await axios.put('/class/class', classData.value)
    console.log(response);
    if (response.data.code === 200){
      ElMessage.success("更新成功")
      fetchData();
      ClassDetailUpdateVisible.value = false;
    } else if (response.data.message === '班级代码重复') {
      ElMessage.error("班级代码重复")
      fetchData();
    } else {
      ElMessage.error("更新失败")
      fetchData();
    }
  } catch (error) {
    console.log(error)
  }
}

/**
 * 表格选择变化处理
 * @param selection
 */
const handleSelectionChange = (selection) => {
  selectedStudents.value = selection
}

/**
 * 添加学生，打开弹窗
 * @param rowData
 */
const addStudent = async (rowData) => {

  // 保存当前操作的班级信息
  currentClass.value = rowData

  // 重置选中的学生
  selectedStudents.value = []

  /**
   * 获取学生列表
   */
  try {
    const response = await axios.get('/stu/student/class/list', {
      params: rowData
    })
    console.log('学生列表:', response);
    studentTableData.value = response.data.data || [];
  } catch (error) {
    console.error('获取学生列表失败:', error);
    ElMessage.error('获取学生列表失败')
  }

  ClassStudentManageVisible.value = true;
}

/**
 * 删除学生打开弹窗
 */
const deleteStudent = async (rowData) => {

  // 保存当前操作的班级信息
  currentClass.value = rowData

  // 重置选中的学生
  selectedStudents.value = []

  /**
   * 获取学生列表（当前班级）
   */
  try {
    const response = await axios.get('/stu/student/class/list/' + rowData.classCode)
    console.log('学生列表:', response);
    studentTableData.value = response.data.data || [];
  } catch (error) {
    console.error('获取学生列表失败:', error);
    ElMessage.error('获取学生列表失败')
  }

  ClassStudentDeleteVisible.value = true;
}

/**
 * 添加学生，真正添加
 */
const addStudentRel = async () => {
  if (selectedStudents.value.length === 0) {
    ElMessage.warning('请至少选择一个学生')
    return
  }

  try {
    // 提取所有选中学生的学号
    const selectedSnoList = selectedStudents.value.map(student => student.sno)

    // 构建请求数据
    const requestData = {
      classCode: currentClass.value.classCode,
      className: currentClass.value.name,
      selectedSnoList: selectedSnoList
    }

    console.log('发送的数据:', requestData)

    const response = await axios.post('/class/class/addStudents', requestData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.data.code === 200) {
      ElMessage.success('添加学生成功')
      // 关闭弹窗
      ClassStudentManageVisible.value = false
      // 刷新班级数据
      fetchData()
    } else {
      ElMessage.error('添加学生失败: ' + response.data.message)
    }
  } catch (error) {
    console.error('添加学生失败:', error)
    ElMessage.error('添加学生失败: ' + error.message)
  }
}

/**
 * 删除学生，真正删除
 */
const deleteStudentRel = async () => {
  if (selectedStudents.value.length === 0) {
    ElMessage.warning('请至少选择一个学生')
    return
  }

  try {
    // 提取所有选中学生的学号
    const selectedSnoList = selectedStudents.value.map(student => student.sno)

    // 构建请求数据
    const requestData = {
      classCode: currentClass.value.classCode,
      className: currentClass.value.name,
      selectedSnoList: selectedSnoList
    }

    console.log('发送的数据:', requestData)

    const response = await axios.post('/class/class/deleteStudents', requestData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.data.code === 200) {
      ElMessage.success('删除学生成功')
      // 关闭弹窗
      ClassStudentDeleteVisible.value = false
      // 刷新班级数据
      fetchData()
    } else {
      ElMessage.error('删除学生失败: ' + response.data.message)
    }
  } catch (error) {
    console.error('删除学生失败:', error)
    ElMessage.error('删除学生失败: ' + error.message)
  }
}

/**
 * 新增
 */
const insertClass = async () => {
  // 验证表单
  await insertFormRef.value.validate()

  console.log(classData.value)
  try {
    const response = await axios.post('/class/class', classData.value,  {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    //console.log(response);
    if (response.data.code === 200){
      window.alert("新增成功")
      fetchData();
      ClassInsertDialogVisible.value = false;
    } else if (response.data.message === '班级代码重复') {
      ElMessage.error("班级代码重复")
      fetchData();
    } else {
      ElMessage.error("新增失败")
      fetchData();
    }
  } catch (error) {
    console.log(error)
  }
}

</script>


<style scoped>
.upload-dropdown {
  padding: 10px;
}
.upload-dropdown :deep(.el-upload-list) {
  max-height: 150px;
  overflow-y: auto;
  margin-top: 10px;
}
</style>